package logic

import (
	"bytes"
	"context"
	"encoding/json"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
	"month2/C/rpc_C/model/es"
	"month2/C/rpc_C/model/mysql"
	"strconv"
	"sync"

	"month2/C/rpc_C/internal/svc"
	"month2/C/rpc_C/order"

	"github.com/zeromicro/go-zero/core/logx"
)

type EsSyncGoodsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewEsSyncGoodsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EsSyncGoodsLogic {
	return &EsSyncGoodsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *EsSyncGoodsLogic) EsSyncGoods(in *order.EsSyncGoodsRequest) (*order.EsSyncGoodsResponse, error) {
	var (
		list []*mysql.Goods1
		wg   sync.WaitGroup
	)
	for _, goods := range list {
		wg.Add(1)
		go func(goods *mysql.Goods1) {
			defer wg.Done()
			// Build the request body.
			data, err := json.Marshal(goods)
			if err != nil {
				log.Fatalf("Error marshaling document: %s", err)
			}
			// Set up the request object.
			req := esapi.IndexRequest{
				Index:      "goods",
				DocumentID: strconv.Itoa(int(goods.ID)),
				Body:       bytes.NewReader(data),
				Refresh:    "true",
			}
			// Perform the request with the client.
			res, err := req.Do(context.Background(), es.Es)
			if err != nil {
				log.Fatalf("Error getting response: %s", err)
			}
			defer res.Body.Close()
		}(goods)
	}
	wg.Wait()
	return &order.EsSyncGoodsResponse{}, nil
}
